import axios from 'axios'
import global from '../global.json'
import qs from "qs"
import store from '../store'

let request = axios.create({
    baseURL: global.baseURL,  // api的base_url
    timeout: 5000             // 请求超时时间
})

/****** 请求拦截器 ******/
request.interceptors.request.use(
    config => {
        store.state.LOADING = true
        let token = store.state.TOKEN
        let requestFormatData = {
            token : token,
            data : config.data
        }
        config.method === 'get'
            ? config.params = {...config.data}
            : config.data = qs.stringify(requestFormatData)

        config.headers['token'] = token
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        console.log( 'REQ:',config )
    return config
}, error => {  //请求错误处理
    console.log('error')
    return Promise.reject(error)
})

/****** 返回拦截器  ******/
request.interceptors.response.use(
    response => {  //成功请求到数据
        sended()
        let resultCode = {
            "200":function (){
                console.log( 'RES:',response )
                return response.data
            },
            "500":function(){
                console.error('500')
            }
        }
        return resultCode[ response.status ]()
        // return response
    },
    error => {  //响应错误处理
        sended()
        console.error('error')
        return Promise.reject(error)
    }
)

function sended(){
    store.state.LOADING = false
}

export default request